package com.diancan;

import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.SqlLiteDB.MenuDataHelper;
import com.Utils.JsonUtils;
import com.Utils.MenuUtils;
import com.Utils.FileUtils;
import com.declare.Declare;
import com.mode.DeskObj;
import com.mode.History;
import com.mode.MenuListDataObj;
import com.mode.SelectedProduct;
import com.model.AllDomain;
import com.model.Category;
import com.model.Desk;
import com.model.Recipe;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;

public class Main extends TabActivity {
    
	/** Called when the activity is first created. */
	private TabHost m_tabHost;
	private TabWidget m_tabWidget;
	AlertDialog.Builder alertDialog;
	AlertDialog.Builder confirmDialog;
	ProgressDialog progressDialog=null;
	DataReceiver dataReceiver;
	Resources rsResources;
	BroadcastReceiver receiver;	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); 
        setContentView(R.layout.main);
        //获取应用全局变量   
        Declare declare=(Declare)getApplicationContext();
        
        DeskObj deskObj=null;
        String jsonString="";
        try {
			jsonString=FileUtils.ReadDingDan(this);
			deskObj=JsonUtils.ParseJsonToDeskObj(jsonString);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
        
        History history=null;
        jsonString="";
        try {
			jsonString=FileUtils.ReadHistory(this);
			history=JsonUtils.ParseJsonToHistory(jsonString);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        if(deskObj!=null)
        {
        	declare.curDeskObj=deskObj;
        }
        if(history!=null)
        {
        	declare.history=history;
        }
        else {
			declare.history=new History();			
		}
        //初始化必要的全局变量
        declare.menuListDataObj=new MenuListDataObj();
//        declare.categoryMap=new HashMap<String,String>();
        declare.deskList=new ArrayList<DeskObj>();
        declare.deskHashMaps=new ArrayList<HashMap<String,Object>>();  
        
        rsResources=getResources();
        FileUtils._dbPathFile=new File(rsResources.getString(R.string.db_folder));
        FileUtils._dbFileFile=new File(rsResources.getString(R.string.db_file));
        FileUtils._imgPathFile=new File(rsResources.getString(R.string.img_folder));
        FileUtils.cacheDir = this.getExternalCacheDir();
        MenuUtils.initUrl="http://"+rsResources.getString(R.string.url_service);
        MenuUtils.updateUrl="http://"+rsResources.getString(R.string.url_service);
        MenuUtils.imageUrl="http://"+rsResources.getString(R.string.image_service);
        alertDialog=new AlertDialog.Builder(Main.this);
        alertDialog.setTitle(rsResources.getString(R.string.title_errdialog));
        alertDialog.setPositiveButton(rsResources.getString(R.string.okstr_dialog), new DialogInterface.OnClickListener() {
        	@Override
			 public void onClick(DialogInterface dialog, int which) {
				 dialog.cancel();
		}});
        
//        if(!FileUtils._dbFileFile.exists())
//		{
//        	FileUtils.Createdbfile();
//        	MenuDataHelper.OpenDatabase();
//        	MenuDataHelper.CreateMenusTable();
//        	MenuDataHelper.CloseDatabase();
//		}

        m_tabHost = getTabHost();  
        m_tabHost.setup();
        m_tabHost.bringToFront();
        
        addMenuListTab();
        addMyTableTab();
        addMyServiceTab();
        addHistoryTab();
        m_tabHost.setCurrentTab(0);
        m_tabWidget = (TabWidget)findViewById(android.R.id.tabs);
        m_tabWidget.setStripEnabled(false);
      //注册一个广播接收器，启动餐桌抖动动画  
      receiver = new BroadcastReceiver() {
    	@Override
        public void onReceive(Context ctx, Intent intent) {
    		if (intent.getAction().equals("animation")) {
   			 Animation animation2=AnimationUtils.loadAnimation(Main.this, R.anim.txtviewanim);
   			 View v=m_tabHost.getTabWidget().getChildAt(1);
   			 v.startAnimation(animation2);  
    		}
    	}
    };
    IntentFilter filter = new IntentFilter();
    filter.addAction("animation");
    filter.addCategory(Intent.CATEGORY_DEFAULT);
    registerReceiver(receiver, filter);
        
    }
    private View populateTabItem(int imageResourceSelector, String text) {  
  
        View view = View.inflate(this, R.layout.tab_item, null); 
        ((ImageView) view.findViewById(R.id.tab_item_imageview))  
                .setImageResource(imageResourceSelector);  
        ((TextView) view.findViewById(R.id.tab_item_textview)).setText(text);  
        return view;
    }
    public void addMenuListTab(){  
        Intent intent = new Intent();  
        intent.setClass(Main.this, MenuGroup.class); 
        View v=populateTabItem(R.drawable.drinks, rsResources.getString(R.string.title_Tab1));
	    m_tabHost.addTab(m_tabHost.newTabSpec("menu1").setIndicator(v).setContent(intent));
}  
    public void addMyTableTab(){  
        Intent intent = new Intent();  
        intent.setClass(Main.this, MyTable.class);  
        View v=populateTabItem(R.drawable.mytable, rsResources.getString(R.string.title_Tab2));
	    m_tabHost.addTab(m_tabHost.newTabSpec("menu2").setIndicator(v).setContent(intent));
} 
    public void addMyServiceTab(){  
        Intent intent = new Intent();  
        intent.setClass(Main.this, MyService.class);     
        View v=populateTabItem(R.drawable.myservice, rsResources.getString(R.string.title_Tab3));
	    m_tabHost.addTab(m_tabHost.newTabSpec("menu3").setIndicator(v).setContent(intent));
    }  
    public void addHistoryTab(){  
        Intent intent = new Intent();  
        intent.setClass(Main.this, HistoryGroup.class);     
        View v=populateTabItem(R.drawable.ic_launcher, rsResources.getString(R.string.title_Tab4));
	    m_tabHost.addTab(m_tabHost.newTabSpec("menu4").setIndicator(v).setContent(intent));
    }  
   
  	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
  		Declare declare=(Declare)getApplicationContext();
 		
  		String deskstr=JsonUtils.ConvertDeskObjToJson(declare.curDeskObj);
  		String hisStr=JsonUtils.ConvertHistoryToJson(declare.getHistory());
    	try {
			FileUtils.SaveDingDan(this, deskstr);
			FileUtils.SaveHistory(this, hisStr);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	declare.curDeskObj=null;
    	declare.history=null;
    	declare.menuListDataObj=null;
//    	declare.categoryMap=null;
    	declare.deskList=null;
    	declare.deskHashMaps=null;

//    	if(MenuDataHelper.IsOpened())
//    	{
//    		MenuDataHelper.CloseDatabase();
//    	}
    	unregisterReceiver(receiver);
		super.onDestroy();
	}
  //重写onTouchEvent,这里的目的是把touch事件传给子视图
  	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
    	return this.getCurrentActivity().onTouchEvent(event);
	}
  	private class DataReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
        	setProgressBarIndeterminateVisibility(false);
        	Toast toast = Toast.makeText(Main.this, rsResources.getString(R.string.toaststr_updateok), Toast.LENGTH_SHORT); 
        	toast.show(); 
        	Intent myIntent = new Intent();
          myIntent.setAction(MenuUtils.UPDATE_SERVICE);
          myIntent.putExtra("cmd", MenuUtils.CMD_STOP_SERVICE);
          sendBroadcast(myIntent);
        }                
	}
}